package com.huyn.baseframework.dynamicload;

import android.content.Context;

import com.huyn.baseframework.model.ThemeModel;
import com.huyn.baseframework.utils.StringUtils;
import com.ryg.dynamicload.internal.DLPluginPackage;

import java.util.HashMap;

/**
 * Created by huyaonan on 16/5/26.
 */
public class PluginPackageManager {

    private static PluginPackageManager mInstance;

    private HashMap<String, DLPluginPackage> mModulePkgMaps;

    private ThemeModel mTheme;

    private PluginPackageManager() {
    }

    public static synchronized PluginPackageManager getInstance() {
        if(mInstance == null)
            mInstance = new PluginPackageManager();
        return mInstance;
    }

    public boolean hasModule(String id) {
        if(mModulePkgMaps != null && mModulePkgMaps.containsKey(id))
            return true;
        return false;
    }

    public DLPluginPackage getModule(String id) {
        if(mModulePkgMaps != null)
            return mModulePkgMaps.get(id);
        return null;
    }

    public void putModule(String code, DLPluginPackage pkg) {
        if(mModulePkgMaps == null)
            mModulePkgMaps = new HashMap<>();
        mModulePkgMaps.put(code, pkg);
    }

    public DLLayout inflatePluginLayout(Context context, String modelCode, String clazzName, boolean isWidget) {
        try {
            if(StringUtils.isBlank(modelCode) || StringUtils.isBlank(clazzName))
                return null;
            DLPluginPackage pkg = getModule(modelCode);
            DLClassInflate inflate = DynamicLoaderHelper.loadTargetClass(context, pkg, clazzName);
            if(inflate == null)
                return null;
            String clazz = isWidget ? inflate.getWidgetClass() : inflate.getListItemClass();
            return DynamicLoaderHelper.loadTargetLayout(context, pkg, clazz);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public DLLayout inflatePluginLayout(Context context, DLPluginPackage pkg, String clazzName, boolean isWidget) {
        try {
            DLClassInflate inflate = DynamicLoaderHelper.loadTargetClass(context, pkg, clazzName);
            if(inflate == null)
                return null;
            String clazz = isWidget ? inflate.getWidgetClass() : inflate.getListItemClass();
            return DynamicLoaderHelper.loadTargetLayout(context, pkg, clazz);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public ThemeModel getTheme() {
        return mTheme;
    }

    public void updateTheme(ThemeModel theme) {
        this.mTheme = theme;
    }

}
